package th.retrofit.lib;

import java.util.List;

public class Solution61 {

    public ListNode rotateRight(ListNode head, int k) {
        int length = 0;
        ListNode tail = head;
        while (tail != null) {
            length++;
            tail = tail.next;
        }
        if (length == 0) return head;
        k = k % length;
        if (k == 0) return head;
        int offset = length - k;
        tail = head;
        while (offset > 1) {
            offset--;
            tail = tail.next;
        }
        ListNode n2 = tail.next;
        tail.next = null;
        ListNode newHead = n2;
        while (k > 1) {
            k--;
            n2 = n2.next;
        }
        n2.next = head;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(new Solution61().rotateRight(l1, 2));
    }

}
